package ua.sumdu.LukyanovChalyi.Client;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
import javax.xml.parsers.*;
import org.xml.sax.SAXException;
import ua.sumdu.LukyanovChalyi.Utils.*;
import ua.sumdu.LukyanovChalyi.Server.*;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;

public class FromServerThread implements Runnable {

    private InputStream in;
    private View view;

    public FromServerThread(InputStream in, View view) {
        this.in = in;
        this.view = view;
    }

    @Override
    public void run() {
        try {
            while (true) {
                parseXMLFromServer();
            }
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                view.showException("Input stream doesn't close", e);
            }
        }
    }

    public void parseXMLFromServer() {
        try {
            XMLUtils utils = new XMLUtils();
            Document doc = utils.getDocument(in);
            Element root = doc.getDocumentElement();
            String command = root.getElementsByTagName(Transport.COMMAND).item(0).getFirstChild().getNodeValue();
            if (Transport.SHOW_BOOKS.equals(command)) {
                List<CopyBook> list = new LinkedList<CopyBook>();
                Element library = doc.getDocumentElement();
                NodeList books = library.getElementsByTagName(XMLUtils.COPY_BOOK);
                for (int i = 0; i < books.getLength(); i++) {
                    CopyBook addBook = utils.readCopyBook((Element) books.item(i));
                    list.add(addBook);
                }
                view.showBooks(list);
            } else if (Transport.SHOW_MESSAGE.equals(command)) {
                String message = root.getElementsByTagName(Transport.MESSAGE).item(0).getFirstChild().getNodeValue();
                view.showMessage(message);
            }
        } catch (SAXException e) {
            view.showException("SAXException while parsing xml", e);
        } catch (ParserConfigurationException e) {
            view.showException("Serious configuration error", e);
        } catch (IOException e) {
            view.showException("Server is unavailable", e);
            System.exit(0);
        }
    }
}